/**
 * 详情对话框
 */
var PurchaseOrderInfoDlg = {
    data: {
        poSerial: "",
        poAgent: "",
        poAgentDept: "",
        poSupplierName: "",
        poSumAmount: "",
        poSumNumbers: "",
        poStatus: "",
        poRemark: "",
        name: "",
        id:""
    }
};


layui.use(['form', 'admin', 'ax', 'layedit', 'table', 'tableSelect', 'layer'], function () {
    var $ = layui.jquery;
    var $ax = layui.ax;
    var form = layui.form;
    var admin = layui.admin;
    var layedit = layui.layedit;
    var lay_table = layui.table;
    var table_select = layui.tableSelect;
    var layer = layui.layer;

    //让当前iframe弹层高度适应
    admin.iframeAuto();


    //富文本
    var index = layedit.build('poRemark');


    $("#backPage").click(function () {
        window.location.href = Feng.ctxPath + "/purchaseOrder";
    });


    //选择产品属性插件
    $("#name_1").click(function () {
        var formName = encodeURIComponent("parent.PurchaseOrderInfoDlg.data.name");
        var formId = encodeURIComponent("parent.PurchaseOrderInfoDlg.data.id");
        var treeUrl = encodeURIComponent(Feng.ctxPath + "/classification/getTree");

        layer.open({
            type: 2,
            title: '分类选择',
            area: ['300px', '150px'],
            content: Feng.ctxPath + '/system/commonTree?formName=' + formName + "&formId=" + formId + "&treeUrl=" + treeUrl,
            end: function () {
                $("#classification").val(PurchaseOrderInfoDlg.data.id);
                $("#name_1").val(PurchaseOrderInfoDlg.data.name);
            }
        });
    });



    //表单提交事件
    form.on('submit(btnSubmit)', function (data) {

        var ajax = new $ax(Feng.ctxPath + "/price/submit", function (data) {
            if (data.code === 500) {
                Feng.error("错误:" + data.message)
            } else {
                Feng.success("添加成功!");
            }
            //传给上个页面，刷新table用
            admin.putTempData('formOk', true);

            //关掉对话框
            admin.closeThisDialog();
        }, function (data) {
            Feng.error("添加失败！" + data.responseJSON.message)
        });
        var PurchaseCost = lay_table.cache['purchaseCost'];

        var requestData = [];

        var errorInfo = "";

        if (!Katrina.isEmpty(errorInfo)) {
            Feng.info(errorInfo);
            return false;
        }

        PurchaseCost.forEach(function (val, index, arr) {
            var price = {};
            price.levelId = val.warhouseLevelId;
            price.productPrice = val.productPrice;
            requestData.push(price);
        });
        // for (var i = 0; i < productDetail.length; i++) {
        //     var product = {};
        //     product.orderProductId = productDetail[i].productId;
        //     product.orderPrice = productDetail[i].productTaxIncludedUnitPrice;
        //     product.orderNumbers = productDetail[i].orderNumbers;
        //     product.orderAmount = productDetail[i].orderAmount;
        //     product.orderRemark = productDetail[i].remark;
        //     product.orderUnit = productDetail[i].unitsId;
        //     product.orderIsGifts = productDetail[i].orderIsGifts === true ? 1 : 0;
        //     productDetails.push(product);
        // }
        data.field['purchaseCost'] = JSON.stringify(PurchaseCost);



        var productId = $("#classification").val();
        console.log("产品di是："+productId);
        ajax.set(data.field);
        ajax.set("productId", productId);
        ajax.start();
        window.location.href = Feng.ctxPath + "/price";
        return false;

    });

    //费用表格
    lay_table.render({
        elem: '#purchaseCost'
        , toolbar: '#toolbar_two'
        , title: ''
        , cellMinWidth: 100
        , totalRow: true
        , data: []
        , cols: [[
            {type: 'numbers', title: '序号', rowspan: 2, fixed: 'left'},
            {field: 'costPurchaseAmount', sort: true, title: '金额', edit: "number"},
            {field: 'warhouseLevel', title: '选择经销商等级', event: 'setUnit', rowspan: 2},
            {field: 'warhouseLevelId', sort: false, title: '等级id',hide:true},
            {align: 'center', toolbar: '#tableBar_two', title: '操作'}
        ]],
        page: false, done: function (e) {
        }
    });

    //头工具栏事件
    lay_table.on('toolbar(purchaseCost)', function (obj) {
        var checkStatus = lay_table.checkStatus(obj.config.id);
        switch (obj.event) {
            case 'add':
                var tableData = lay_table.cache['purchaseCost'];
                var item = {};
                item.warhouseLevelId = "";
                item.warhouseLevel = "";
                item.costPurchaseAmount = "填写金额";
                tableData.push(item);
                lay_table.reload('purchaseCost', {
                    data: tableData
                });
                break;
            case 'getCheckLength':
                var data = checkStatus.data;
                layer.msg('选中了：' + data.length + ' 个');
                break;
            case 'isAll':
                layer.msg(checkStatus.isAll ? '全选' : '未全选');
                break;
        }
    });

    lay_table.on('edit(purchaseCost)', function (obj) {
        var value = obj.value; //得到修改后的值
        var data = obj.data;
        if (parseFloat(data.costPurchaseCash).toFixed(4) > 0) {
            obj.update({
                costPurchaseStatus: 1
            });
        } else {
            obj.update({
                costPurchaseStatus: 0
            });
        }
    });

    lay_table.on('tool(purchaseCost)', function (obj) {
        var data = obj.data;
        if (obj.event === 'setCostPurchaseName') {
            layer.prompt({
                formType: 2
                , title: '填写费用名称，如:住宿费'
                , value: data.costPurchaseName === "填写费用名" ? "" : data.costPurchaseName
            }, function (value, index) {
                layer.close(index);
                obj.update({
                    costPurchaseName: value
                });

            });
        } else if (obj.event === 'remark') {
            layer.prompt({
                formType: 2
                , title: '备注'
                , value: data.costPurchaseRemark
            }, function (value, index) {
                layer.close(index);
                obj.update({
                    costPurchaseRemark: value
                });

            });
        } else if (obj.event === 'selectAccount') {
            top.layui.admin.open({
                type: 2,
                area: ["600px", "650px"],
                title: '兑现账户',

                content: Feng.ctxPath + '/table_select/account_select',
                end: function () {
                    var account = admin.getTempData("account");
                    if (account !== undefined || account != null) {
                        obj.update({
                            costPurchaseAccountName: account.name,
                            costPurchaseAccount: account.id
                        });
                    } else {
                        Feng.error("数据异常!")
                    }
                }, cancel: function () {

                }
            });
        }else if (obj.event === 'setUnit'){
            layer.open({
                title: "⚙ 经销商等级",
                type: 2,
                skin: 'layui-layer-admin',
                content: [Feng.ctxPath + '/level/level'], //这里content是一个URL，如果你不想让iframe出现滚动条，你还可以content: ['http://sentsin.com', 'no']
                area: ['500px', '205px'],
                end: function (){
                    var unit = admin.getTempData('ok');
                    console.log(unit);
                    console.log(unit.id);
                    console.log(unit.name);
                    obj.update({
                        warhouseLevel: unit.name,
                        warhouseLevelId: unit.id
                        //orderAmount: getAmount(data.conversionRatio,data.unitId,data.orderNumbers,data.price)
                    });
                    //console.log(getAmount(data.conversionRatio,data.id, data.orderNumbers,data.price));
                    lay_table.reload('purchaseCost', {
                        data: lay_table.cache['purchaseCost']
                    });
                }, cancel: function () {
                    obj.update({
                        warhouseLevelId: data.warhouseLevelId
                        //orderAmount: getAmount(data.conversionRatio,data.unitId,data.price, data.orderNumbers)
                    });
                    lay_table.reload('purchaseCost', {
                        data: lay_table.cache['purchaseCost']
                    });
                }
            });
        } else {
            layer.confirm('确定?', function (index) {
                obj.del();
                layer.close(index);
            });
        }
    });
});
